import https from 'https';
import CryptoJS from 'crypto-js';
import querystring from 'querystring';
// 引入配置文件
import { CUSTOM_ROBOT_TOKEN , SECRET } from '@/config.js';
// 生成签名
function generateSign(timestamp, secret) {
    const stringToSign = `${timestamp}\n${secret}`;
    const hmac = CryptoJS.HmacSHA256(stringToSign, secret);
    const signData = hmac.toString(CryptoJS.enc.Base64);
    return encodeURIComponent(signData);
}

// 发送请求到钉钉机器人
export async function sendMessageToDingTalk(messageData) {
    const timestamp = Date.now();
    const sign = generateSign(timestamp, SECRET);

    // 构建请求 URL
    const url = `/Dingapi/robot/send?access_token=${CUSTOM_ROBOT_TOKEN}&timestamp=${timestamp}&sign=${sign}`;

    const postData = JSON.stringify(messageData);

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: postData
        });
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}
    
const date = new Date();
const formattedTime = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    
function formatErrorInfo(error) {
    return `# LX 系统监控告警 🚨

**⚠️ 接口异常信息**
- 状态码：${error.statusCode}
- 请求方法：${error.method}
- 请求路径：${error.path}
- 完整 URL：${error.fullUrl}
- 时间：${formattedTime}
- 请求参数：${JSON.stringify(error.params)}

**错误详情**：${error.message}`;
}

export async function handleError(errorMessage) {
    const formattedError = formatErrorInfo(errorMessage);
    console.error(formattedError);

    const message = {
        msgtype: 'markdown',
        markdown: {
            title: 'LX 系统监控告警',
            text: formattedError
        },
        at: {}
    };

    const postData = JSON.stringify(message);
    const timestamp = Date.now();
    const sign = generateSign(timestamp, SECRET);
    const url = `/Dingapi/robot/send?access_token=${CUSTOM_ROBOT_TOKEN}&timestamp=${timestamp}&sign=${sign}`;

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: postData
        });
        console.log(response);
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error(error);
    }
}

// 发送错误信息到钉钉机器人
// handleError(formattedError);

// process.on('uncaughtException', handleError);
// process.on('unhandledRejection', handleError);

// 调用发送消息函数
// sendMessageToDingTalk();

